//
//  ContactsTools.m
//  Birthday Reminder
//
//  Created by Andrei Marcu on 10/23/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ContactsTools.h"
#import "BirthdayItem.h"


@implementation ContactsTools

+ (NSArray *)getContactsArrayWithBirthdays {
    NSMutableArray *returnedArray = [[[NSMutableArray alloc] init] autorelease];
    BirthdayItem *item;
    ABAddressBookRef addressBook = ABAddressBookCreate();
    CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
    NSInteger numberOfContacts = (NSInteger)ABAddressBookGetPersonCount(addressBook);
    for (int i = 0; i < numberOfContacts; ++i) {
        ABRecordRef ref = CFArrayGetValueAtIndex(allPeople,i);
        NSString *recodID = [NSString stringWithFormat:@"%d", (NSInteger)ABRecordGetRecordID(ref)];
        NSString *firstName = (NSString *)ABRecordCopyValue(ref, kABPersonFirstNameProperty);
        NSString *lastName = (NSString *)ABRecordCopyValue(ref, kABPersonLastNameProperty);
        NSDate *birthdate = (NSDate *)ABRecordCopyValue(ref, kABPersonBirthdayProperty);
        NSData *imageData = (NSData *)ABPersonCopyImageData(ref);
        UIImage *image = nil;
        if (imageData != nil) {
            image = [UIImage imageWithData:imageData];
        }
        if (birthdate != nil) {
            item = [[BirthdayItem alloc] init];
            [returnedArray addObject:item];
            item.birthDate = birthdate;
            item.image = image;
            item.recordID = recodID;
            NSString *name = @"";
            if (firstName != nil) {
                if (lastName != nil) {
                    name = [NSString stringWithFormat:@"%@ %@", firstName, lastName];
                } else {
                    name = firstName;
                }
            } else {
                name = lastName;
            }
            item.name = name;
            [item release];
        }
        [firstName release];
        [lastName release];
        [birthdate release];
        [imageData release];
        image = nil;
    }
    CFRelease(allPeople);
    CFRelease(addressBook);
    return returnedArray;
}

@end
